import InteractionUtil from '../../shell/ui/interaction';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: '',
    address1: '',
    address2: '',
    location: '',
    addressList: [],
    index: 0,
    selectIndex: -1,
    wxAddress: '',
    locationAddress: {}
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    getApp().getSaleMode()
    wx.getStorage({
      key: 'position',
      success: (res) => {
        const { data } = res
        const { address } = data
        const { type, wxAddress, locationAddress } = address
        if (type * 1 === 1) {
          this.setData({
            address,
            location: address.address,
            address1: address.address,
            address2: wxAddress,
            wxAddress,
            locationAddress,
            index: 1
          })
          this.getNearAddress(locationAddress || address)
          this.initLocation(1)
        } else if (type === 2) {
          this.getNearAddress(locationAddress || address).then(_ => {
            const { addressList } = this.data
            const selectIndex = addressList.findIndex(item => item.address === address.address)
            this.setData({
              address,
              location: address.address,
              address1: address.address,
              address2: wxAddress,
              wxAddress,
              index: 2,
              selectIndex
            })
          })
          this.initLocation(1)
        } else {
          this.setData({
            address,
            location: address,
            address1: address.address,
            address2: wxAddress,
            wxAddress,
            index: 0
          })
          this.getNearAddress(locationAddress || address)
        }
      }
    })
  },

  getNearAddress: async function (data) {
    const { latitude, longitude } = data
    const url = (latitude * 1 === 0 || !latitude) ? 'getHistoryAddress' : 'getNearbyAddress'
    return await wx.$http().request({ url: `/AppMaster/AgentUnion/${url}`, method: 'POST', data: latitude * 1 === 0 ? { location_type: 'gps' } : Object.assign(data, { location_type: 'gps' }) }).then(res => {
      const { _data } = res
      const { address_list } = _data.data
      this.setData({
        addressList: address_list
      })
    })
  },
  initLocation(flag = 0) {
    flag = typeof flag === 'number' ? 1 : 0
    wx.getSetting({
      success: res => {
        if (typeof (res.authSetting['scope.userLocation']) === "undefined") { // 从未触发过授权的情况
          wx.getLocation({ // 用户同意授权地理位置
            success: (res) => {
              this.getAddress(res, flag)
            },
            fail: err => { // 用户拒绝授权地理位置
              this.getAddress(res, flag)
            }
          })
        } else if (!res.authSetting['scope.userLocation']) {
          this.getAddress(res)
        } else if (res.authSetting['scope.userLocation']) {
          wx.getLocation({ // 用户同意授权地理位置
            success: (res) => {
              this.getAddress(res, flag)
            }
          })
        }
      }
    })
  },
  getAddress(res, flag) {
    const { latitude, longitude } = res
    const { locationAddress } = this.data
    wx.$http().request({ url: '/AppMaster/AgentUnion/getMyAddress', method: 'POST', data: { longitude, latitude, is_select_address: 0, location_type: 'gps' } }).then(res => {
      const { _data } = res
      if (flag * 1 === 0) {
        this.setData({
          location: _data.data,
          // address1: _data.data.address,
          locationAddress: flag === 1 ? locationAddress : _data.data,
          // index: 0
        })
        wx.setStorage({
          key: 'position',
          data: { address: _data.data }
        })
        this.getNearAddress(flag === 1 ? locationAddress : _data.data)
      } else {
        this.setData({
          location: _data.data,
          locationAddress: _data.data
        })
      }
    })
  },
  selectAddress(e) {
    const { dataset } = e.currentTarget
    const { index } = dataset
    const { addressList } = this.data
    const selectAddress = addressList[index]
    this.setData({
      address1: selectAddress.address,
      index: 2,
      selectIndex: index
    })
    let { address, wxAddress, locationAddress } = this.data
    if (address.address !== selectAddress.address) {
      wx.$http().request({
        url: 'AppMaster/AgentUnion/selectAddress',
        data: Object.assign(selectAddress, { location_type: 'gps' }),
        method: 'POST'
      }).then(_ => {
        const { _data } = _
        const { result } = _data
        if (result === 0) {
          const { location } = selectAddress
          if (location) {
            const longitude = location.split(',')[0]
            const latitude = location.split(',')[1]
            address = Object.assign(selectAddress, { longitude, latitude, type: 2, wxAddress, locationAddress })
          } else {
            address = Object.assign(selectAddress, { type: 2, wxAddress, locationAddress })
          }
          this.setData({
            address,
          })
          wx.setStorage({
            key: 'position',
            data: { address },
            success: _ => {
              wx.navigateBack()
            }
          })
        }
      })
    } else {
      wx.navigateBack()
    }
  },
  chooseAddress() {
    wx.chooseAddress({
      success: res => {
        const { provinceName, cityName, countyName, detailInfo, userName } = res
        const selectAddress = provinceName + cityName + countyName + detailInfo
        const { address } = this.data
        this.setData({
          address2: selectAddress + ' ' + userName,
          wxAddress: selectAddress + ' ' + userName
        })
      }
    })
  },
  confirmAddress(e) {
    const { dataset } = e.currentTarget
    const { address, type } = dataset
    const { location, address2, wxAddress, locationAddress } = this.data
    if (type * 1 === 1) {
      if (address === '') {
        InteractionUtil.showNotice('请先完善地址')
        return
      }
    }
    this.setData({
      address1: address,
      index: type
    })
    const param = type * 1 === 0 ? location : { address: address2.split(' ')[0] }
    wx.$http().request({
      url: 'AppMaster/AgentUnion/selectAddress',
      data: Object.assign(param, { location_type: 'gps' }),
      method: 'POST'
    }).then(_ => {
      const { _data } = _
      const { result } = _data
      if (result === 0) {
        const r = type * 1 === 0 ? Object.assign({}, location, { type: 0, wxAddress, locationAddress }) : { address: address2, type: 1, wxAddress, locationAddress }
        wx.setStorage({
          key: 'position',
          data: { address: r },
          success: () => {
            wx.navigateBack()
          }
        })
      }
    })
  }
})